package array;

public class MaxProfit {
    public static void main(String[] args) {
        int[] nums = {7,1,5,3,6,4};
        int solution = new MaxProfit().solution2(nums);
        System.out.println(solution);
    }
    public int solution(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }
        int max = 0;
        for (int i = 0; i < prices.length; i++) {
            int maxProfit = 0;
            for (int j = i + 1; j < prices.length; j++) {
                maxProfit = Math.max(maxProfit, prices[j]);
            }
            max = Math.max(max, maxProfit - prices[i]);
        }
        return max;
    }
    public int solution2(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }
        int cost = 0;
        int max = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            if(prices[i + 1] > cost){
                max += prices[i + 1] - prices[i];
                cost = prices[i + 1];
            }else{
                cost = prices[i + 1];
            }
        }
        return max;
    }
}
